/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;


/**
 *
 * @author Carlos
 */

public class entradausuario extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        SocialFP red;
        try{
               GestorPersistencia.crearConexion();
        }catch(ErrorConexionBD e){
                  notificarError (request, response, "Error", "Error al  conectar con la BBDD");     
                }
        red=new SocialFP();
             
                 try {
                    red.recuperaUjaenSocial();
                }catch (Exception e){
                 notificarError (request, response, "Error", "No se puede recuperar el estado de la red");
                }
        request.getSession ().setAttribute ("red", red);
        
        if (request.getParameter("registro")!=null)
            crearUsuario(request,response,red);
        else
            if (request.getParameter("login")!=null)
              buscarUsuario(request,response,red);
             else
                notificarError(request,response,"Error", "Acceso ilegal");
    
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    
    protected void crearUsuario (HttpServletRequest request, HttpServletResponse response, SocialFP red)
        throws ServletException, IOException
    {
       String email;
       String clave;
       String nombre;
       String descripcion;
       Usuario u;
        
      
        
        email = request.getParameter ("email");
        clave = request.getParameter ("passwd");
        nombre = request.getParameter ("nombre");
        descripcion = request.getParameter ("descripcion");
        if (email == null || email=="") {
            notificarError (request, response, "Error en datos de usuario", "Debe indicar el email.");
            return;
        }
        if (clave == null || clave=="") {
            notificarError (request, response, "Error en datos de cuenta", "Debe indicar una clave.");
            return;
        }
        if (nombre == null || nombre =="") {
            notificarError (request, response, "Error en datos de cuenta", "Debe indicar un nombre.");
            return;
        }
               
        u = new Usuario (email, clave, nombre, descripcion);
        try{
            red.nuevoUsuario(u);
        }catch (Exception e){
            notificarError (request, response, "Error", "El user no ha podido ser insertado.");
            return;
        }
        request.getSession ().setAttribute ("email", email);
        request.getSession ().setAttribute ("clave", clave);
        
        //GestorPersistencia.desconectar();
        notificarExito (request, response, "OK", "Estás dentro de la red");
        //RequestDispatcher dispatcher = request.getRequestDispatcher(response.encodeURL("mostrarUsuario"));
        //dispatcher.forward (request, response);
    }
    
    protected void buscarUsuario (HttpServletRequest request, HttpServletResponse response,SocialFP red)
        throws ServletException, IOException
    {
        String email;
        String clave;
        Usuario u;
       
        
        email = request.getParameter ("emaillog");
        clave = request.getParameter ("passwdlog");
        u=red.loginUsuario(email, clave);
        
                
        if (u==null) {
            notificarError (request, response, "Error de búsqueda", "El usuario no existe.");
            return;
        }
        
        
        request.getSession ().setAttribute ("email", email);
        request.getSession ().setAttribute ("clave", clave);
        notificarExito (request, response, "OK", "Estás dentro de la red"); 
        //GestorPersistencia.desconectar();
        //RequestDispatcher dispatcher = request.getRequestDispatcher(response.encodeURL("mostrarUsuario"));
        //dispatcher.forward (request, response);
    }
    protected void notificarExito (HttpServletRequest request, HttpServletResponse response, String cabecera, String descripcion) 
        throws ServletException, IOException
    {
        RequestDispatcher dispatcher = request.getRequestDispatcher("realizado.jsp?cabecera=" + cabecera 
                + "&descripcion=" + descripcion + "&continuar=mostrarUsuario");
        dispatcher.forward (request, response);    
    }
    
    protected void notificarError (HttpServletRequest request, HttpServletResponse response, String cabecera, String descripcion) 
        throws ServletException, IOException
    {
        RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp?cabecera=" + cabecera 
                + "&descripcion=" + descripcion + "&continuar=index.html");
        dispatcher.forward (request, response);    
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
